package com.ldg.order.controller;

import com.alipay.api.AlipayApiException;
import com.ld.pojo.PayAsyncVo;
import com.ld.pojo.PayVo;
import com.ld.pojo.TbPayLog;
import com.ld.utils.AlipayTemplate;
import com.ldg.order.entity.TbOrder;
import com.ldg.order.service.OrderService;
import com.ldg.order.service.PayService;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Author: Liudao
 * @Date: 2022-10-20-19:32
 * @Description:
 */
@Controller
public class PayController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private PayService payService;

    //订单支付
    @GetMapping("/order/pay/{type}")
    @ResponseBody
    public String pay(@PathVariable int type, String outTradeNo, HttpSession session) throws AlipayApiException {
        //1.1 得到登录名
        Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        String str = "";
        if(assertion != null) {
            //1.2 得到用户名
            String name = assertion.getPrincipal().getName();
            //1.3 从redis中查询中PayVo对象
            PayVo vo = orderService.findPayVoByname(name);
            //1.4 通过alipayTemplate得到支付宝支付返回的页面
            str = alipayTemplate.pay(vo, type);

        }
        return str;
    }

    //支付后的同步回调，return_url指向的地址，显示所有订单列表
    //显示所有订单列表
    @GetMapping("order/orderlist")
    public String orderList(Model model, HttpSession session){
        //1.1 得到登录名
        Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        if(assertion != null) {
            //1.2 得到用户名
            String name = assertion.getPrincipal().getName();
            //1.3 根据用户名查询订单
            List<TbOrder> orderList = orderService.findOrdersByName(name);
            //1.4 放到model中
            model.addAttribute("orderlist",orderList);
        }
        return "orderlist";
    }

    //支付后的异步回调，Notify_url指向的地址，更新数据库支付相关表的信息
    @PostMapping("/order/payed/notify")
    @ResponseBody
    public String DBAfterPay (PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {
        //将请求参数转换为map
        HashMap<String, String> params = new HashMap<>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //2.2 验签、更新支付日志、更新订单表的状态
        return  payService.payNotify(vo,params);
    }

    //测试页面（专用于测试，不然每次都得重新添加订单）
//    @GetMapping("/payPage")
//    public String payPage(HttpSession session, Model model){
//        //1.1 得到登录名
//        Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
//        if(assertion != null) {
//            //1.2 得到用户名
//            String name = assertion.getPrincipal().getName();
//            //1.4 根据用户名得到支付日志
//            TbPayLog payLog = orderService.findPayLogByUname(name);
//            model.addAttribute("paylog",payLog);
//        }
//        return "pay";
//    }

}
